import requests
import os,json

# 设置存储文件夹
fileDir = "爬取的音乐"
if not os.path.exists(fileDir):
    os.mkdir(fileDir)
    print("存放下载音乐的文件夹不存在，已帮您创建名为“{}”的文件夹".format(fileDir))

# 设置请求头
headers = {
    'Cookie': 'td_cookie=1911283501; kw_token=YT75BGHHGKD; Hm_lvt_cdb524f42f0ce19b169a8071123a4797=1623413157; Hm_lpvt_cdb524f42f0ce19b169a8071123a4797=1623413355; _ga=GA1.2.2059815838.1623413158; _gid=GA1.2.1861134441.1623413158; _gat=1',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0',
    'csrf': 'YT75BGHHGKD',
    'Referer': 'http://www.kuwo.cn/search/list?key=%E9%82%93%E7%B4%AB%E6%A3%8B'
}

# 通过rid下载音乐
def getMusic(rid, name):
    url = '	http://www.kuwo.cn/url?format=mp3&rid={}&response=url&type=convert_url3&br=128kmp3&from=web&t=1623417976109&httpsStatus=1&reqId=996294e1-cab8-11eb-88b7-371073d1d442'.format(rid)
    # 发起一个请求
    result = requests.get(url, headers=headers).json()
    musicUrl = result['url']
    with open(fileDir+'/{}.mp3'.format(name), 'wb') as f:
        music = requests.get(musicUrl)
        f.write(music.content)
        print('{},下载完成'.format(name))

# 定位查找的音乐资源
def main():
    singer = str(input('请输入歌手名称：'))
    number = int(input('请输入下载页数：'))
    songsCont = 0
    for pn in range(1,number+1):
        # print("pn:{}".format(pn))
        # 资源地址
        url = 'http://www.kuwo.cn/api/www/search/searchMusicBykeyWord?key={}&pn={}&rn=30&httpsStatus=1&reqId=995fd5c0-cab8-11eb-88b7-371073d1d442'.format(singer,pn)
        # 发起网络请求
        response = requests.get(url, headers=headers).json()
        data = response['data']['list']
        for index in data:
            rid = index['rid']
            name = index['name']

            getMusic(rid, name)
            songsCont += 1
        print("所需下载的歌曲全部下载完成，共下载{}首音乐，存放在“{}”文件夹。".format(songsCont,fileDir))

main()